<?php


namespace app\models\user;


use think\Model;
use app\Redis;

class UserToken extends Model
{
    protected $name = 'user_token';

    protected $type = [
        'create_time' => 'datetime',
        'login_ip' => 'string'
    ];

    protected $autoWriteTimestamp = true;

    protected $updateTime = false;

    protected static $token_pre = 'token_';

    public static function onBeforeInsert(UserToken $token)
    {
        if (!isset($token['login_ip']))
            $token['login_ip'] = app()->request->ip();
    }

    /**
     * 创建token并且保存
     * @param User $user
     * @param $type
     * @return UserToken
     */
    public static function createToken(User $user, $type): self
    {
        $tokenInfo = $user->getToken($type);
        //清除旧 token 保证单点有效
        self::where('uid',$user->uid)->delete();

        $data=[
            'uid' => $user->uid,
            'token' => $tokenInfo['token'],
            'expires_time' => date('Y-m-d H:i:s', $tokenInfo['params']['exp'])
        ];
        //token写入redis
        $key=self::$token_pre.$user->uid;
        Redis::set($key,$data);
        return self::create($data);
    }

    /**
     * 查询验证token
     * @param $token
     * @return UserToken
     */
    public static function getToken($uid,$token)
    {
        if(!$uid || !$token){
            return [];
        }
        $key=self::$token_pre.$uid;
        $data=Redis::get($key);
        if(!$data){
            $data=self::where('uid',$uid)->where('token',$token)->find();
            if($data){
                $data=$data->toArray();
            }
        }
        if($data){
            $nowtime=time();
            if($nowtime>strtotime($data['expires_time'])){
                return [];
            }
        }
        return $data;
    }

    /**
     * 删除一天前的过期token
     * @return bool
     * @throws \Exception
     */
    public static function delToken()
    {
        return self::where('expires_time', '<', date('Y-m-d H:i:s',strtotime('-1 day')))->delete();
    }

    /**
     * 删除token
     * @return bool
     * @throws \Exception
     */
    public static function del($where)
    {
        return self::where($where)->delete();
    }
}